<?php

declare(strict_types=1);

namespace App\Listener;

use App\Event\AdminActionLog;
use App\Model\AdminActionLog as Log;
use Hyperf\Event\Annotation\Listener;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Event\Contract\ListenerInterface;

/**
 * @Listener
 */
class AdminActionLogListener implements ListenerInterface {
    /**
     * @var RequestInterface
     */
    private $request;

    public function __construct(RequestInterface $request) {
        $this->request = $request;
    }

    public function listen(): array {
        return [
            AdminActionLog::class
        ];
    }

    /**
     * @param AdminActionLog $event
     */
    public function process($event) {
        // 写入日志记录
        $admin = $this->request->getAttribute('admin');
        Log::query()->insert([
            'admin_id' => $admin['id'],
            'admin_name' => $admin['name'],
            'type' => $event->type,
            'ip' => $this->request->getHeaderLine('x-forwarded-for'),
            'log' => $event->log,
        ]);
    }
}
